<?php
/**
 * File缓存驱动器
 * @author Tongle Xu <xutongle@gmail.com> 2012-10-31
 * @copyright Copyright (c) 2003-2103 yuncms.net
 * @license http://leaps.yuncms.net
 * @version $Id: File.php 623 2013-07-29 03:40:03Z 85825770@qq.com $
 */
class Cache_File extends Cache {
	
	/**
	 * 缓存后缀
	 * var string
	 */
	public $cacheFileSuffix = '.bin';
	
	/**
	 * 缓存保存路径
	 *
	 * @var string
	 */
	public $cachePath = '';
	
	/**
	 * 是否子目录保存
	 *
	 * @var boolean
	 */
	private $isDirectory = false;
	
	/**
	 * (non-PHPdoc)
	 *
	 * @see Cache::init()
	 */
	public function init() {
		parent::init ();
		if (! is_dir ( $this->cachePath )) @mkdir ( $this->cachePath, 0777, true );
	}
	
	/**
	 * (non-PHPdoc)
	 *
	 * @see Cache::setValue()
	 */
	protected function setValue($key, $value, $expire = 0) {
		$cacheFile = $this->getCacheFile ( $key );
		if ($this->isDirectory) @mkdir ( dirname ( $cacheFile ), 0777, true );
		if (@file_put_contents ( $cacheFile, $value, LOCK_EX ) !== false) {
			@chmod ( $cacheFile, 0777 );
			return @touch ( $cacheFile, $expire );
			;
		} else
			return false;
	}
	
	/**
	 * (non-PHPdoc)
	 *
	 * @see Cache::getValue()
	 */
	protected function getValue($key) {
		$cacheFile = $this->getCacheFile ( $key );
		return @file_get_contents ( $cacheFile );
	}
	
	/**
	 * (non-PHPdoc)
	 *
	 * @see Cache::deleteValue()
	 */
	protected function deleteValue($key) {
		$cacheFile = $this->getCacheFile ( $key );
		return @unlink ( $cacheFile );
	}
	
	/**
	 * (non-PHPdoc)
	 *
	 * @see Cache::flushValues()
	 */
	public function flushValues() {
		$this->gc ();
		return true;
	}
	
	/**
	 * 获取文本缓存要存放的路径
	 *
	 * @param string $key 缓存数据的唯一key
	 */
	private function getCacheFile($key) {
		if (strpos ( $key, '.' ) !== false) {
			$key = str_replace ( '.', DIRECTORY_SEPARATOR, $key );
			$this->isDirectory = true;
		}
		return $this->cachePath . DIRECTORY_SEPARATOR . $key . $this->cacheFileSuffix;
	}
	
	/**
	 * 删除所有缓存文件
	 *
	 * @param string $path 路径
	 */
	public function gc($path = null) {
		if ($path === null) $path = $this->cachePath;
		if (($handle = opendir ( $path )) === false) return;
		while ( ($file = readdir ( $handle )) !== false ) {
			if ($file [0] === '.') continue;
			$fullPath = $path . DIRECTORY_SEPARATOR . $file;
			if (is_dir ( $fullPath ))
				$this->gc ( $fullPath );
			else {
				@unlink ( $fullPath );
			}
		}
		closedir ( $handle );
	}
}